<template>
  <div>
    <div class="box">
      <van-icon name="arrow-left" @click="$router.go(-1)" />
      <!-- 引用自定义指令 -->
      <van-search @input="change()" @search="search(value)" v-fofo v-model="value" shape="round" clearable
        background="#3296fa" placeholder="请输入搜索关键词" />
    </div>

    <div class="sugg-list">
      <div v-if="value !== ''">
        <div>搜索建议</div>
        <!-- 由于使用了html标签所以需要v-html解析 -->
        <div class="sugg-item" v-for="(item, index) in data" :key="index" v-html="lightFn(item, value)"
          @click="search(item)"></div>
      </div>

      <div v-else style="width:100%">
        <div class="title">搜索历史
          <van-icon name="delete" @click="delFn()"/>
        </div>
        <van-row gutter="6" type="flex" align="10">
          <van-col span="6" v-for="item in history" :key="item">
            <van-button type="default" round @click="search(item)">{{ item }}</van-button>
          </van-col>
        </van-row>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'seach',
  data () {
    return {
      value: '',
      data: [],
      // 字符串转数组取出
      history: JSON.parse(this.$storage.getStorage('his')) || []
    }
  },
  watch: {
    history: {
      deep: true, // 深度监听数组的变化,变化后存入缓存
      handler () {
        // 数组转字符串存入缓存
        this.$storage.setStorage('his', JSON.stringify(this.history))
      }
    }
  },
  methods: {
    async change () {
      if (this.value.length === 0) {
        this.data = []
      } else {
        if (this.value.length === 0) return
        const { data: res } = await this.$api.suggestionAPI({ q: this.value })
        this.data = res.data.options
      }
    },
    // 处理文字高亮
    lightFn (str, target) {
      if (str !== null) {
        // str原来的字符串
        // target关键字
        // 找到str中的关键字然后使用html标签进行替换
        // replaceAll替换全部符合条件的
        // 正则表达式中使用变量
        const reg = new RegExp(target, 'ig') // i忽略大小写,g全局匹配
        // 避免将原来的数据替换掉，所以用函数形式展示匹配到字符并且只设置颜色
        return str.replace(reg, (marth) => {
          return `<span style="color:red";>${marth}</span>`
        })
      }
    },
    search (e) {
      if (e.length > 0) {
        this.history.push(e)// 跳转前存入数据
        // 用set去重,处理完形成一个对象所以需要用Array.from转回数组
        this.history = Array.from(new Set(this.history))
        // 动态路由需要拼接
        setTimeout(() => {
          this.$router.push({
            path: `/seachResult/${e}`
          })
        }, 5)
      }
    },
    delFn () {
      this.history = []
    }
  }
}
</script>

<style lang="less" scoped>
.box {
  display: flex;
  align-items: center;
  background: #3296fa;
}

.sugg-list {
  display: flex;
  flex-direction: column;
  padding: 10px 15px;
  align-items: flex-start;
  font-size: 18px;
  overflow: hidden;

  .sugg-item {
    display: flex;
    height: 35px;
    align-items: center;
    width: 100%;
    border-bottom: 1px solid #f8f8ff;
  }
}

/deep/ .van-icon-arrow-left {
  color: #fff;
  font-size: 18px;
  margin-left: 15px;
}

/deep/.van-search {
  width: 100%
}

/deep/ .van-button {
  background: #f4f5f6;
  font-size: 15px;
  width: 100%;
  margin-bottom: 6px;
}

/deep/ .van-button--normal {
  padding: 0;
}

.title {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
</style>
